package com.amoyt.project.security.filter;


import com.amoyt.project.config.redis.RedisCache;
import com.amoyt.project.constants.RedisConstants;
import com.amoyt.project.domain.bo.LoginUser;
import com.amoyt.project.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;
import java.util.UUID;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // ！！！在开始处理前，清空 SecurityContextHolder，确保每个请求都是独立的
        SecurityContextHolder.clearContext();

        //1.获取token
        String token = request.getHeader("Token");

        if (!StringUtils.hasText(token)) {
            //为空放行
            log.info("Token为空");
            //相当于压根未登录
            try {
                filterChain.doFilter(request, response);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
            return;
        }

        //2.解析token
        String userId = null;

        try {
            Claims claims = jwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            log.info("Token解析失败: {}", e.getMessage());
            SecurityContextHolder.clearContext();
            filterChain.doFilter(request, response);
            return;
        }

        //从redis中获取用户信息
        String redisKey = RedisConstants.LOGIN_USER_KEY_PRE + userId;
        LoginUser loginUser = (LoginUser) redisCache.getCacheObject(redisKey);

        //TODO 缓存中没有，可能是缓存宕机了

        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
            //TODO 可以做一个具体响应

        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

        //设置进去
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request, response);
    }
}